<template>
  <div class="container">
    <form action="/">
      <van-search
          v-model="value"
          show-action
          placeholder="请输入搜索的标签"
          @search="onSearch"
          @cancel="onCancel"
      />
    </form>
    <div class="history-search">
      <h2 class="history-search-title">已添加自定义标签</h2>



      <div class="history-search-list">
        <a-input-tag
            v-model="customList"
            :style="{width:'320px'}"
            placeholder="输入自定义添加的标签"
            allow-clear
            max-tag-count="6"
            unique-value/>
<!--        <van-tag v-for="tag in customList" closeable size="small" type="primary" @close="doClose(tag)">-->
<!--          {{ tag }}-->
<!--        </van-tag>-->


<!--        <van-tag-->
<!--            v-for="(item, index) in historyList"-->
<!--            :key="index"-->
<!--            :show="historyShow"-->
<!--            size="medium"-->
<!--            type="primary"-->
<!--            @click="doSearch(item)"-->
<!--        >-->
<!--          {{ item }}-->
<!--        </van-tag>-->
      </div>
    </div>
    <hr />

    <div class="select-tags">
      <h2 class="select-tags-title">标签栏</h2>
      <div>
        <van-tabs v-model:active="active" swipeable>
          <van-tab
              v-for="(item, index) in tags"
              :title="item.title"
              :key="index"
              sticky
          >
            <div class="select-tags-tag">
              <van-tag
                  @close="selectTagClose(iitem)"
                  color="#48b0e8"
                  :plain="!iitem.isActive"
                  :closeable="iitem.isActive"
                  size="large"
                  v-for="(iitem, iindex) in item.content"
                  :key="iindex"
                  @click="selectTags(iitem)"
              >{{ iitem.name }}</van-tag
              >
            </div>
          </van-tab>
        </van-tabs>
      </div>

      <div class="search-toolbar">
        <van-button block type="primary" @click="doSearchRrsult">
          搜索
        </van-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref, watchEffect} from 'vue'
import {showFailToast, showToast} from 'vant'
import { useRouter } from 'vue-router'
import tagList from "../constants/tagList";
// import { getUserRecord } from '@/api/search'

type content = {
  id: number
  name: string
  isActive: boolean
}

type tag = {
  title: string
  content: Array<content>
}[]
// 标签数据
let tags = ref<tag>(tagList);

// 选择标签
const active = ref(0)
const value = ref('')
const router = useRouter()
const onSearch = (val: string) => {
  showToast(val)
  // 在tags中查找是否有相同的标签，并使active选中该标签的id
  tags.value.forEach((item, index) => {
    item.content.forEach(iitem => {
      if (iitem.name === val) {
        active.value = index
      }
    })
  })
}

// const maxTagsNum = 1;
// const disabledInput = ref(false);
// const handlePressEnter = (val) => {
//   const isExist = ref(false);
//   selectTagNameList.value.forEach(item => {
//     console.log("val:" + val);
//     if (item === val) {
//       showFailToast('该标签已存在');
//       isExist.value = true;
//     }
//
//   })
//
//   if (!isExist.value) {
//     console.log("selectTagNameList.value.length:" + selectTagNameList.value.length);
//     if (selectTagNameList.value.length+1 <= maxTagsNum) {
//       selectTagNameList.value.push(customInputValue.value);
//       disabledInput.value = false;
//     } else {
//       disabledInput.value = true;
//       showFailToast(`最多只能输入${maxTagsNum}个标签！`);
//     }
//   }
// };

const onCancel = () => {
  router.back()
}

const customList = ref<String[]>([]);
const customTag = ref([]);
const customInputValue = ref<String>();
// 添加自定义标签
const onAddTag = (val) => {
  const isExist = ref(false);
  customList.value.forEach(item =>{
    if (item === val.customTag) {
      showFailToast('该标签已存在');
      isExist.value = true;
    }
  })
  if (!isExist.value) {
    customList.value.push(val.customTag);
  }
};

//移除标签
const doClose = (tag) => {
  customList.value = customList.value.filter(item => {
    return item !== tag; //表达式为true才会保留这个标签
  })
};



// 搜索
const historyShow = ref(true)
const historyList = ref([])
// const getHistory = async () => {
//   // 获取历史搜索
//   const res = await getUserRecord()
//   if (res.status === 200) {
//     historyList.value = res.data
//   }
// }
const doSearch = (item: string) => {
  router.push({
    path: '/user/list',
    query: {
      tags: JSON.stringify([item])
    }
  })
}

const selectTagNameList = ref<String[]>([])
const selectTags = (item: content) => {
  item.isActive = !item.isActive
  // 选中的标签
  if (item.isActive) {
    selectTagNameList.value.push(item.name)
  } else {
    selectTagNameList.value = selectTagNameList.value.filter(
        (i: any) => i !== item.name
    )
  }
  console.log(selectTagNameList.value)
}
const selectTagClose = (item: content) => {
  item.isActive = !item.isActive
  selectTagNameList.value = selectTagNameList.value.filter(
      (i: any) => i !== item.name
  )
  console.log(selectTagNameList.value)
}

// 搜索结果
const maxTagsNum = 6;
const doSearchRrsult = () => {
  const totalTagList = ref<String[]>([]);

  selectTagNameList.value.forEach(item => {
    totalTagList.value.push(item);
  });
  customList.value.forEach(item => {
    totalTagList.value.push(item);
  });

  if (totalTagList.value.length === 0) {
    showToast('请选择标签')
    return
  }else if(totalTagList.value.length >maxTagsNum) {
    showFailToast(`最多只能输入${maxTagsNum}个标签！`);
    return;
  }
  // console.log("JSON.stringify(selectTagNameList.value):" + selectTagNameList.value);
  router.push({
    path: '/user/list',
    query: {
      tags: totalTagList.value,
    }
  })
}

// onMounted(() => {
//   getHistory()
// })
</script>

<style lang="scss" scoped>
@import '../assets/css/search';
</style>







<!--<template>-->
<!--  <form action="/">-->
<!--    <van-search-->
<!--        v-model="searchText"-->
<!--        show-action-->
<!--        placeholder="请输入搜索的标签"-->
<!--        @search="onSearch"-->
<!--        @cancel="onCancel"-->
<!--    >-->
<!--      &lt;!&ndash;      <van-row gutter="20">&ndash;&gt;-->
<!--      &lt;!&ndash;        <van-col v-for="tag in activeIds">&ndash;&gt;-->
<!--      &lt;!&ndash;          <van-tag closeable size="small" type="primary" @close="doClose(tag)">&ndash;&gt;-->
<!--      &lt;!&ndash;            {{ tag }}&ndash;&gt;-->
<!--      &lt;!&ndash;          </van-tag>&ndash;&gt;-->
<!--      &lt;!&ndash;        </van-col>&ndash;&gt;-->
<!--      &lt;!&ndash;      </van-row>&ndash;&gt;-->
<!--    </van-search>-->
<!--  </form>-->
<!--  <van-divider content-position="left">已选标签</van-divider>-->
<!--  <div v-if="activeIds.length === 0">请选择标签</div>-->
<!--  <van-row gutter="20">-->
<!--    <van-col v-for="tag in activeIds">-->
<!--      <van-tag closeable size="small" type="primary" @close="doClose(tag)">-->
<!--        {{ tag }}-->
<!--      </van-tag>-->
<!--    </van-col>-->
<!--  </van-row>-->

<!--  <van-form @submit="onAddTag">-->
<!--    <van-cell-group inset>-->
<!--      <van-field-->
<!--          v-model="customTag"-->
<!--          center-->
<!--          name="customTag"-->
<!--          label="自定义标签"-->
<!--          placeholder="输入想要搜索用户的标签"-->
<!--          :rules="[{ required: true, message: '标签不能为空' }]"-->
<!--      >-->
<!--        <template #button>-->
<!--          <van-button block size="small" type="primary" icon="plus" native-type="submit" />-->
<!--        </template>-->
<!--      </van-field>-->
<!--    </van-cell-group>-->
<!--  </van-form>-->

<!--  <van-divider content-position="left">选择标签</van-divider>-->
<!--  <van-tree-select-->
<!--      v-model:active-id="activeIds"-->
<!--      v-model:main-active-index="activeIndex"-->
<!--      :items="tagList"-->
<!--  />-->
<!--  <div style="padding: 12px">-->
<!--    <van-button type="primary" @click="doSearchResult" block>搜索用户</van-button>-->
<!--  </div>-->

<!--</template>-->

<!--<script setup lang="ts">-->
<!--import { ref } from 'vue';-->
<!--import {showFailToast, showToast} from 'vant';-->
<!--import {useRouter} from "vue-router";-->
<!--import UserTagsList from "../constants/UserTagsList";-->

<!--const router = useRouter();-->
<!--const searchText = ref('');-->
<!--const customTag = ref('');-->

<!--//搜索下面的选择标签中有没有要搜索的标签并把它标记。-->
<!--const onSearch = (val) => {-->
<!--  tagList.value = UserTagsList.map(parentTag => {-->
<!--    const tempChildren = [...parentTag.children]; //把parentTag.children数组中的数据取出来，放到一个新的数组tempChildren中-->
<!--    const tempParentTag = {...parentTag};-->
<!--    tempParentTag.children = tempChildren.filter(item => item.text.includes(searchText.value));-->
<!--    return tempParentTag;-->
<!--  });-->
<!--}-->
<!--const onCancel = () => {-->
<!--  searchText.value = '';-->
<!--  tagList.value = UserTagsList;-->
<!--}-->

<!--//已选中的标签-->
<!--const activeIds = ref([]);-->
<!--const activeIndex = ref(0);-->

<!--//移除标签-->
<!--const doClose = (tag) => {-->
<!--  activeIds.value = activeIds.value.filter(item => {-->
<!--    return item !== tag; //表达式为true才会保留这个标签-->
<!--  })-->
<!--};-->

<!--// 添加标签-->
<!--const onAddTag = (val) => {-->
<!--  const isExist = ref(false);-->
<!--  activeIds.value.forEach(item =>{-->
<!--    if (item === val.customTag) {-->
<!--      showFailToast('该标签已存在');-->
<!--      isExist.value = true;-->
<!--    }-->
<!--  })-->
<!--  if (!isExist.value) {-->
<!--    activeIds.value.push(val.customTag);-->
<!--  }-->
<!--};-->


<!--/**-->
<!-- * 执行搜索-->
<!-- */-->
<!--const doSearchResult = () => {-->
<!--  // console.log("activeIds.value:" + activeIds.value);-->
<!--  router.push({-->
<!--    path: '/user/list',-->
<!--    query: {-->
<!--      tags: activeIds.value-->
<!--    }-->
<!--  });-->
<!--};-->

<!--let tagList = ref(UserTagsList);-->

<!--</script>-->

<!--<style scoped>-->

<!--</style>-->